package de.blinkt.openvpn;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;

public class NetworkUtil {
	private static final String DEFAULT_WIFI_NETWORK_NAME = "WIFI";


	public static NetworkInfo getCurrentNetworkInfo(Context context) {
		ConnectivityManager conn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = conn.getActiveNetworkInfo();
		return networkInfo;
	}
	
	
	public static String extractNetworkName(Context context, NetworkInfo info) {
		if (info.getType() == ConnectivityManager.TYPE_WIFI) {
			// if WIFI: get info from WIFI servcice
			WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
			if (wifiManager.getConnectionInfo() != null) {
				return wifiManager.getConnectionInfo().getSSID();
			} else {
				return DEFAULT_WIFI_NETWORK_NAME;
			}
		} else if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
			TelephonyManager telephonyManager = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE));
			return telephonyManager.getNetworkOperatorName();
		} else {
			throw new IllegalArgumentException("Unknown Network Type: " + info.getType() + "(" + info.getTypeName() + ")");
		}
	}


	public static boolean networkMatches(Context context, NetworkInfo networkInfo, int networkType, int networkSubtype, String networkName) {
		//have seen where subtype is not consistently reported for the same network
		if(networkInfo.getType() == networkType /*&& networkInfo.getSubtype() == networkSubtype*/){
			try {
				if(NetworkUtil.extractNetworkName(context, networkInfo).equals(networkName)){
					return true;
				} 
			} catch (IllegalArgumentException e){
			
			}
		}
		
		return false;

	}


	public static boolean sameNetwork(Context c, NetworkInfo n1, NetworkInfo n2) {
		if(n1 == null && n2 == null){
			return true;
		} else if(n1 == null && n2 != null){
			return false;
		} else if(n1 != null && n2 == null){
			return false;
		} else if(n1.getType() == n2.getType() && n1.getSubtype() == n2.getSubtype()){
			try {
				String name1 = extractNetworkName(c, n1);
				String name2 = extractNetworkName(c, n2);
				return name1.equals(name2);
			} catch (IllegalArgumentException e){
				return false;
			}
		} else {
			return false;
		}
		
		
	}
	
}
